/*
 * (c) rdrrlabs gmail com, 2011
 * Project: 24ClockWidget
 * License GPLv3
 */

package com.rdrrlabs.a24clock.prefs;

import com.alfray.a24clock.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.CheckBoxPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.RelativeLayout;

//-----------------------------------------------

public class CheckBoxPreference2 extends CheckBoxPreference {

    /** True if {@link #shouldDisableDependents()} works as inverted. */
    private boolean mNegDep;
    private float mExtraLeftMargin;
    private int mOriginalLeftMargin = -1;

    public CheckBoxPreference2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initAttrs(context, attrs);
    }

    public CheckBoxPreference2(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
    }

    public CheckBoxPreference2(Context context) {
        super(context);
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CheckBoxPref2);
        if (a != null) {
            mNegDep = a.getBoolean(R.styleable.CheckBoxPref2_negativeDependency, false);
            mExtraLeftMargin = a.getDimension(R.styleable.CheckBoxPref2_extraLeftMargin, 0);
        }
    }

    @Override
    public boolean shouldDisableDependents() {
        boolean d = super.shouldDisableDependents();
        if (mNegDep) d = !d;
        return d;
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);

        if (view instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) view;
            int n = vg.getChildCount();
            for (int i = 0; i < n; i++) {
                View v = vg.getChildAt(i);
                if (v instanceof RelativeLayout) {
                    LayoutParams lp = v.getLayoutParams();
                    if (lp instanceof MarginLayoutParams) {
                        MarginLayoutParams mlp = (MarginLayoutParams) lp;
                        if (mOriginalLeftMargin < 0) {
                            mOriginalLeftMargin = mlp.leftMargin;
                        }
                        mlp.leftMargin = (int) (mOriginalLeftMargin + mExtraLeftMargin);
                    }
                    break;
                }
            }
        }
    }
}
